package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.MessageFuncEnum;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.entity.AppUser;
import com.uzai.console.entity.Device;
import com.uzai.console.mapper.AppUserMapper;
import com.uzai.console.mapper.WechatUserMapper;
import com.uzai.console.mapper.WxpubUserMapper;
import com.uzai.console.mapper.WxworkUserMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserOperatorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
@Slf4j
public class UserOperatorServiceImpl implements UserOperatorService {

    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    /**
     * 修改会员备注、通讯录备注、已经发送修改手机端备注接口
     *
     * @param user
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Async("taskExecutor")
    public void updateRemarkByUserAndContacts(User user) {
        //个人微信
        if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(user.getDeviceType())) {
            WechatUser wechatUser = new WechatUser();
            BeanUtils.copyProperties(user, wechatUser);
            wechatUser.setMerId(user.getMerId());
            wechatUser.setId(user.getId());
            wechatUser.setVersion(user.getVersion());
            wechatUser.setRemark(user.getRemark());
            wechatUser.setUpdateTime(user.getUpdateTime());
            wechatUserMapper.updateRemark(wechatUser);
        } else if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(user.getDeviceType())) { //企业微信号
            WxworkUser wxworkUser = new WxworkUser();
            BeanUtils.copyProperties(user, wxworkUser);
            wxworkUser.setMerId(user.getMerId());
            wxworkUser.setId(user.getId());
            wxworkUser.setVersion(user.getVersion());
            wxworkUser.setRemark(user.getRemark());
            wxworkUser.setUpdateTime(user.getUpdateTime());
            wxworkUserMapper.updateRemark(wxworkUser);
        } else if (DeviceTypeEnum.WX_PUB.getKey().equals(user.getDeviceType())) { //公众号
            WxpubUser wxpubUser = new WxpubUser();
            BeanUtils.copyProperties(user, wxpubUser);
            wxpubUser.setMerId(user.getMerId());
            wxpubUser.setId(user.getId());
            wxpubUser.setVersion(user.getVersion());
            wxpubUser.setRemark(user.getRemark());
            wxpubUser.setUpdateTime(user.getUpdateTime());
            wxpubUserMapper.updateRemark(wxpubUser);
        } else if (DeviceTypeEnum.APP.getKey().equals(user.getDeviceType())) { //APP
            AppUser appUser = new AppUser();
            BeanUtils.copyProperties(user, appUser);
            appUser.setMerId(user.getMerId());
            appUser.setId(user.getId());
            appUser.setVersion(user.getVersion());
            appUser.setRemark(user.getRemark());
            appUser.setUpdateTime(user.getUpdateTime());
            appUserMapper.updateRemark(appUser);
        }

        //查询该机器人是否存在
        String deviceInfos = user.getDeviceInfos();
        if (StringUtils.isNotBlank(deviceInfos)) {
            try {
                List<Long> deviceUniqueIdList = JSONObject.parseArray(deviceInfos, Long.class);
                if (deviceUniqueIdList != null && deviceUniqueIdList.size() > 0) {
                    for (Long deviceUniqueId : deviceUniqueIdList) {
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, user.getDeviceType(), user.getMerId());
                        if (device != null) {
                            //发送MQ消息
                            MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                            SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                            msgDto.setContent(setUserRemarkDto);
                            msgDto.setId(IdWorker.getId());
                            msgDto.setDeviceUniqueId(device.getId());
                            msgDto.setDeviceType(device.getRecvmsgType());
                            msgDto.setMerId(device.getMerId());
                            msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                            setUserRemarkDto.setWxid(user.getBizUserId());
                            setUserRemarkDto.setRemark(Tools.getStr(user.getRemark()));
                            noticeMsgPushProducerService.setUserRemark(msgDto);

                            //修改通讯录中的备注信息
                            //通过查询运营商其他索引分片获取分片索引
                            String esName = EsIndexName.UZAI_WX_CONTACTS; //默认个人微信
                            //企业微信
                            if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(user.getDeviceType())) {
                                esName = EsIndexName.UZAI_WORKWX_CONTACTS;
                            }
                            String mechantOtherEsIndexName = merchantService.getMechantOtherEsIndexName(esName, user.getMerId());
                            //修改通讯录备注
                            String id = user.getMerId() + "_" + device.getDeviceId() + "_" + user.getBizUserId();
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("remark", user.getRemark());
                            elasticsearchUtilGroupMsg.updateDataById(jsonObject, mechantOtherEsIndexName, id);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("修改会员的通讯录备注失败；userId={}, error={}", user.getId(), e.getMessage());
            }
        }
    }

}
